package com.it.sun.easychat.common.controlleradvice;

import com.it.sun.easychat.model.constant.HttpResponseCode;
import com.it.sun.easychat.model.util.ResultHelper;
import com.it.sun.easychat.model.exception.ApplicationException;
import com.it.sun.easychat.model.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;

/**
 * @author sunmannian
 * @ClassName GlobalControllerAdvice
 * @Date 2020/5/24 16:52
 * @Version V1.0
 * Description  <控制器全局处理器>
 * Copyright (C) 北京中电兴发科技有限公司  since 2020/5/24
 */
@RestControllerAdvice
@Slf4j
public class GlobalControllerAdvice {

    @ExceptionHandler(ApplicationException.class)
    public ResultVO<Void> applicationException(HttpServletResponse response,
                                               ApplicationException e) {
        log.error(e.getMessage(), e);
        response.setStatus(HttpStatus.OK.value());
        return ResultHelper.getFailed(e.getCode(), e.getMessage(), null);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVO<Void> applicationException(HttpServletResponse response,
                                               MethodArgumentNotValidException e) {
        response.setStatus(HttpStatus.OK.value());
        StringBuilder sb = new StringBuilder();
        for (ObjectError allError : e.getBindingResult().getAllErrors()) {
            sb.append(allError.getDefaultMessage()).append(",");
        }
        sb.delete(sb.length() - 1, sb.length());
        return ResultHelper.getFailed(HttpResponseCode.FAILED_CODE, sb.toString(), null);
    }

    /**
     * 其他错误
     */
    @ExceptionHandler({Exception.class})
    public ResultVO<Void> exception(HttpServletResponse response, Exception e) {
        log.error(e.getMessage(), e);
        response.setStatus(HttpStatus.OK.value());
        return ResultHelper.getFailed(HttpStatus.SERVICE_UNAVAILABLE.value(),
                HttpStatus.SERVICE_UNAVAILABLE.getReasonPhrase(), null);
    }
}
